package com.foreveredu.erlms.persist.hibernate;

import java.util.List;

import javax.management.Query;

import org.hibernate.classic.Session;

import com.foreveredu.erlms.domain.News;
import com.foreveredu.erlms.domain.PageModel;
import com.foreveredu.erlms.persist.INewsDao;

public class HibernateNewsDao extends HibernateAbstractDao<News, Integer>
		implements INewsDao {

	private static final long serialVersionUID = 1L;

	public HibernateNewsDao() {
		super(News.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<News> findNewsListView() {
		List<News> news = this.getHibernateTemplate().find(
				"from News n order by n.id desc");
		//如果新闻列表长度超过10条，则只提取前10条新闻
		if (news != null && news.size() > 10) {
			return news.subList(0, 10);
		}
		return news;
	}

	@SuppressWarnings("unchecked")
	@Override
	public PageModel findNewsByPage(int offset) {
		List<News> news = this.getHibernateTemplate().find(
				"from News n order by n.id desc");
		PageModel pm = new PageModel();
		pm.setTotal(news.size());
		if (offset + 10 > news.size()) {
			pm.setDatas(news.subList(offset, news.size()));
			return pm;
		}
		pm.setDatas(news.subList(offset, offset + 10));
		return pm;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public News findNewsByState() {
		List<News> newsList=this.getHibernateTemplate().find("from News n where n.state=?",1);
		News news =null ;
		if (newsList != null && newsList.size() > 0) {
			news = newsList.get(0);
		}
		return news;
	}

	@Override
	@SuppressWarnings("unchecked")
	public News findNewsById(int id) {
		List<News> newsList=this.getHibernateTemplate().find("from News n where n.id=?",id);
		News news =null ;
		if (newsList != null && newsList.size() > 0) {
			news = newsList.get(0);
		}
		return news;
	}
}
